/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.easyioc.context;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.easyioc.config.BeanDefinition;
import com.easyioc.config.ConfigurationReader;
import com.easyioc.config.PropertiesConfigurationReader;
import com.easyioc.support.BeanBuilder;
import com.easyioc.support.SimpleBeanBuilder;
import com.easyioc.util.FileUtils;

/*
 * This class load configuration files from the class path.
 */
public class ClasspathPropertiesBeanContext extends AbstractBeanContext implements BeanContext,
        ConfigurableBeanContext {

	private Map<String, Object> beanRepository = new HashMap<String, Object>();
	private String[] configLocations;

	@Override
	public Object getBean(String beanName) {
		Object bean = beanRepository.get(beanName);
		if (bean == null) {
			throw new BeanCannotFoundException("Bean with the name [ " + beanName + " ] can not be found.");
		}
		return bean;
	}

	@Override
	protected void buildBeans(BeanBuilder beanBuilder, BeanDefinition[] beanDefs) {
		beanRepository = beanBuilder.build(beanDefs);
	}

	@Override
	protected BeanBuilder createBeanBuilder() {
		return SimpleBeanBuilder.getInstance();
	}

	@Override
	protected ConfigurationReader createConfigurationReader() {
		return PropertiesConfigurationReader.getInstance();
	}

	@Override
	protected Collection<File> loadConfigFiles() {
		Collection<File> files = new ArrayList<File>();
		for (String configLocation : configLocations) {
			File file = FileUtils.loadClassPathFile(configLocation);
			files.add(file);
		}
		return files;
	}

	@Override
	public void setConfigLocation(String configLocation) {
		configLocations = configLocation.split(",");
	}

	@Override
	public void setConfigLocations(String[] configLocations) {
		this.configLocations = configLocations;
	}
}
